## ── Attaching packages ─────────────────────────────────────── tidyverse 1.3.1 ──
## ✓ ggplot2 3.3.5     ✓ purrr   0.3.4
## ✓ tibble  3.1.6     ✓ dplyr   1.0.7
## ✓ tidyr   1.1.3     ✓ stringr 1.4.0
## ✓ readr   2.1.2     ✓ forcats 0.5.1
## Warning: package 'tibble' was built under R version 4.1.1
## Warning: package 'readr' was built under R version 4.1.1
## Warning: package 'stringr' was built under R version 4.1.1
## ── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
## x dplyr::filter() masks stats::filter()
## x dplyr::lag()    masks stats::lag()
## Warning: package 'viridis' was built under R version 4.1.1
## Loading required package: viridisLite
## Registering fonts with R
## Warning: package 'plotly' was built under R version 4.1.1
## 
## Attaching package: 'plotly'
## The following object is masked from 'package:ggplot2':
## 
##     last_plot
## The following object is masked from 'package:stats':
## 
##     filter
## The following object is masked from 'package:graphics':
## 
##     layout

Import data from Github

df <- read.csv("https://raw.githubusercontent.com/udialter/intro-to-plotly/main/promotions.csv")

Data adapted from https://open.canada.ca/data/en/dataset/89b12d0b-e844-4470-8123-bd062d27be0b

head(df)
##   Fiscal.Year Female.NCMs.Promoted Male.NCMs.Promoted Total.NCM.Promotions
## 1        1998                  147               1861                 2008
## 2        1999                  146               1727                 1873
## 3        2000                  250               2937                 3187
## 4        2001                  484               4085                 4569
## 5        2002                  476               3743                 4219
## 6        2003                  426               3813                 4239

renaming variables for convenience

df <- df %>%
  rename(Year = 'Fiscal.Year', Female_Promoted = 'Female.NCMs.Promoted', Male_Promoted = 'Male.NCMs.Promoted', Total_promotions = 'Total.NCM.Promotions')
str(df)
## 'data.frame':    23 obs. of  4 variables:
##  $ Year            : int  1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 ...
##  $ Female_Promoted : int  147 146 250 484 476 426 440 485 598 660 ...
##  $ Male_Promoted   : int  1861 1727 2937 4085 3743 3813 3722 3694 3994 4541 ...
##  $ Total_promotions: int  2008 1873 3187 4569 4219 4239 4162 4179 4592 5201 ...

data organizing and restructuring

year <- df$Year
sexf <- rep('Females', nrow(df))
sexm <- rep('Males', nrow(df))
sext <- rep('Total', nrow(df))
fp <- data.frame(year,df$Female_Promoted, sexf) %>% rename(promoted = df.Female_Promoted, sex= sexf)
mp <- data.frame(year,df$Male_Promoted,sexm )%>% rename(promoted = df.Male_Promoted, sex= sexm)
tp <- data.frame(year,df$Total_promotions,sext )%>% rename(promoted = df.Total_promotions,sex =sext)

New data now called df1, year and sex are set as factors

df1 <- rbind(fp,mp,tp)
df1$year <- factor(df1$year)
df1$sex <- factor(df1$sex)

first, creating a ggplot2 object. If issues arise with the font roboto or and error message mentioning polygon (usually in macs),

you can # or delete the hrbrthemes::theme_ft_rc()+ line below (line 45)

p<-ggplot(df1,aes(x=year, y=promoted, group=sex)) +
  geom_line(aes(color=sex), size=1.5)+
  geom_point(aes(color=sex),size = 3)+
  #hrbrthemes::theme_ft_rc()+
  theme(axis.text.x = element_text(angle=45,vjust = 1, hjust=1))

p <- p + scale_color_brewer(palette="Set2")+
  ggtitle("Canadian Armed Forces Officer Promotions by Sex")+
  labs(x = "Year", y="Number of personnel promoted",size=3)

p

ggsave("CAF.png", plot = p, dpi = 700)
## Saving 7 x 5 in image

ggplotly

(intplt<- ggplotly(p, tooltip = c('x',"y","group")))

saving as html object

saveWidget(intplt, "ggplotlyeg.html", selfcontained = F, libdir = "lib/")

some plot_ly fun stuff and examples

dens <- with(diamonds, tapply(price, INDEX = cut, density))
data <- data.frame(
  x = unlist(lapply(dens, "[[", "x")),
  y = unlist(lapply(dens, "[[", "y")),
  cut = rep(names(dens), each = length(dens[[1]]$x)))

fig <- plot_ly(data, x = ~x, y = ~y, z = ~cut, type = 'scatter3d', mode = "lines", color = ~cut, fillcolor= ~cut)

fig
## Warning: 'scatter3d' objects don't have these attributes: 'fillcolor'
## Valid attributes include:
## 'connectgaps', 'customdata', 'customdatasrc', 'error_x', 'error_y', 'error_z', 'hoverinfo', 'hoverinfosrc', 'hoverlabel', 'hovertemplate', 'hovertemplatesrc', 'hovertext', 'hovertextsrc', 'ids', 'idssrc', 'legendgroup', 'legendgrouptitle', 'legendrank', 'line', 'marker', 'meta', 'metasrc', 'mode', 'name', 'opacity', 'projection', 'scene', 'showlegend', 'stream', 'surfaceaxis', 'surfacecolor', 'text', 'textfont', 'textposition', 'textpositionsrc', 'textsrc', 'texttemplate', 'texttemplatesrc', 'transforms', 'type', 'uid', 'uirevision', 'visible', 'x', 'xcalendar', 'xhoverformat', 'xsrc', 'y', 'ycalendar', 'yhoverformat', 'ysrc', 'z', 'zcalendar', 'zhoverformat', 'zsrc', 'key', 'set', 'frame', 'transforms', '_isNestedKey', '_isSimpleKey', '_isGraticule', '_bbox'

## Warning: 'scatter3d' objects don't have these attributes: 'fillcolor'
## Valid attributes include:
## 'connectgaps', 'customdata', 'customdatasrc', 'error_x', 'error_y', 'error_z', 'hoverinfo', 'hoverinfosrc', 'hoverlabel', 'hovertemplate', 'hovertemplatesrc', 'hovertext', 'hovertextsrc', 'ids', 'idssrc', 'legendgroup', 'legendgrouptitle', 'legendrank', 'line', 'marker', 'meta', 'metasrc', 'mode', 'name', 'opacity', 'projection', 'scene', 'showlegend', 'stream', 'surfaceaxis', 'surfacecolor', 'text', 'textfont', 'textposition', 'textpositionsrc', 'textsrc', 'texttemplate', 'texttemplatesrc', 'transforms', 'type', 'uid', 'uirevision', 'visible', 'x', 'xcalendar', 'xhoverformat', 'xsrc', 'y', 'ycalendar', 'yhoverformat', 'ysrc', 'z', 'zcalendar', 'zhoverformat', 'zsrc', 'key', 'set', 'frame', 'transforms', '_isNestedKey', '_isSimpleKey', '_isGraticule', '_bbox'

## Warning: 'scatter3d' objects don't have these attributes: 'fillcolor'
## Valid attributes include:
## 'connectgaps', 'customdata', 'customdatasrc', 'error_x', 'error_y', 'error_z', 'hoverinfo', 'hoverinfosrc', 'hoverlabel', 'hovertemplate', 'hovertemplatesrc', 'hovertext', 'hovertextsrc', 'ids', 'idssrc', 'legendgroup', 'legendgrouptitle', 'legendrank', 'line', 'marker', 'meta', 'metasrc', 'mode', 'name', 'opacity', 'projection', 'scene', 'showlegend', 'stream', 'surfaceaxis', 'surfacecolor', 'text', 'textfont', 'textposition', 'textpositionsrc', 'textsrc', 'texttemplate', 'texttemplatesrc', 'transforms', 'type', 'uid', 'uirevision', 'visible', 'x', 'xcalendar', 'xhoverformat', 'xsrc', 'y', 'ycalendar', 'yhoverformat', 'ysrc', 'z', 'zcalendar', 'zhoverformat', 'zsrc', 'key', 'set', 'frame', 'transforms', '_isNestedKey', '_isSimpleKey', '_isGraticule', '_bbox'

## Warning: 'scatter3d' objects don't have these attributes: 'fillcolor'
## Valid attributes include:
## 'connectgaps', 'customdata', 'customdatasrc', 'error_x', 'error_y', 'error_z', 'hoverinfo', 'hoverinfosrc', 'hoverlabel', 'hovertemplate', 'hovertemplatesrc', 'hovertext', 'hovertextsrc', 'ids', 'idssrc', 'legendgroup', 'legendgrouptitle', 'legendrank', 'line', 'marker', 'meta', 'metasrc', 'mode', 'name', 'opacity', 'projection', 'scene', 'showlegend', 'stream', 'surfaceaxis', 'surfacecolor', 'text', 'textfont', 'textposition', 'textpositionsrc', 'textsrc', 'texttemplate', 'texttemplatesrc', 'transforms', 'type', 'uid', 'uirevision', 'visible', 'x', 'xcalendar', 'xhoverformat', 'xsrc', 'y', 'ycalendar', 'yhoverformat', 'ysrc', 'z', 'zcalendar', 'zhoverformat', 'zsrc', 'key', 'set', 'frame', 'transforms', '_isNestedKey', '_isSimpleKey', '_isGraticule', '_bbox'

## Warning: 'scatter3d' objects don't have these attributes: 'fillcolor'
## Valid attributes include:
## 'connectgaps', 'customdata', 'customdatasrc', 'error_x', 'error_y', 'error_z', 'hoverinfo', 'hoverinfosrc', 'hoverlabel', 'hovertemplate', 'hovertemplatesrc', 'hovertext', 'hovertextsrc', 'ids', 'idssrc', 'legendgroup', 'legendgrouptitle', 'legendrank', 'line', 'marker', 'meta', 'metasrc', 'mode', 'name', 'opacity', 'projection', 'scene', 'showlegend', 'stream', 'surfaceaxis', 'surfacecolor', 'text', 'textfont', 'textposition', 'textpositionsrc', 'textsrc', 'texttemplate', 'texttemplatesrc', 'transforms', 'type', 'uid', 'uirevision', 'visible', 'x', 'xcalendar', 'xhoverformat', 'xsrc', 'y', 'ycalendar', 'yhoverformat', 'ysrc', 'z', 'zcalendar', 'zhoverformat', 'zsrc', 'key', 'set', 'frame', 'transforms', '_isNestedKey', '_isSimpleKey', '_isGraticule', '_bbox'
# MINI PRESENTATION: DEMONSTRATION 
mtcars$am[which(mtcars$am == 0)] <- 'Automatic'
mtcars$am[which(mtcars$am == 1)] <- 'Manual'
mtcars$am <- as.factor(mtcars$am)


fig <- plot_ly(mtcars, x = ~wt, y = ~hp, z = ~qsec, color = ~am, 
               colors = c('#BF382A', '#0C4B8E'))
fig <- fig %>% add_markers(hovertemplate = paste('<b>weight</b>: %{x:.2f}',
                                                 '<br><b>horse power</b>: %{y}<br>',
                                                 '<b>1/4mile/g</b>: %{z}<br>'))
fig <- fig %>% layout(scene = list(xaxis = list(title = 'Weight'),
                                   yaxis = list(title = 'Gross horsepower'),
                                   zaxis = list(title = '1/4 mile time')))
fig
# Diamonds 3D scatter plot
library(plotly)
library(htmlwidgets)
dd <- sample_n(diamonds, size = 50)
figd <- plot_ly(dd, x = ~carat, y = ~price, z = ~depth, color = ~cut)
figd <- figd %>% add_markers(hovertemplate = paste('<b>Price</b>: $%{y:.2f}',
                                                   '<br><b>Carat</b>: %{x}<br>',
                                                   '<b>Diamond Depth</b>: %{z}<br>'))
figd <- figd %>% layout(scene = list(xaxis = list(title = 'Carat'),
                                   yaxis = list(title = 'Price'),
                                   zaxis = list(title = 'Depth')))

figd

#Spiral

count <- 3000

x <- c()
y <- c()
z <- c()
c <- c()

for (i in 1:count) {
  r <- i * (count - i)
  x <- c(x, r * cos(i / 30))
  y <- c(y, r * sin(i / 30))
  z <- c(z, i)
  c <- c(c, i)
}

data <- data.frame(x, y, z, c)

fig <- plot_ly(data, x = ~x, y = ~y, z = ~z, type = 'scatter3d', mode = 'lines',
               line = list(width = 4, color = ~c, colorscale = list(c(0,'#BA52ED'), c(1,'#FCB040'))))

fig